//
//  Toast.m
//  LXShow
//
//  Created by 王敏 on 2016/11/8.
//  Copyright © 2016年 WTFSSD. All rights reserved.
//

#import "Toast.h"

@interface Toast()
@property(nonnull,copy)void(^hiddenComplete)();
@end

@implementation Toast

+(instancetype)Toat:(NSString *)messege duration:(NSTimeInterval)duration{
    return [[self alloc] _initWithFrame:CGRectMake(20, [UIScreen mainScreen].bounds.size.height - 100, [UIScreen mainScreen].bounds.size.width - 40, 30) messege:messege duration:duration];
}

-(id)_initWithFrame:(CGRect)frame messege:(NSString*)messege duration:(NSTimeInterval)duration{
    if(self = [super initWithFrame:frame]){
        self.font = [UIFont systemFontOfSize:14];
        self.textColor = [UIColor whiteColor];
        self.backgroundColor = [UIColor colorWithWhite:0.5 alpha:0.5];
        self.textAlignment = NSTextAlignmentCenter;
        self.numberOfLines = 1;
        self.text = messege;
        [[[UIApplication sharedApplication].delegate window] addSubview:self];
        self.alpha = 0;
        self.frame = (CGRect){frame.origin.x,frame.origin.y + 100,frame.size.width,frame.size.height};
        self.layer.cornerRadius = 5;
        self.layer.masksToBounds = YES;
        
        [UIView animateWithDuration:0.2 animations:^{
            self.frame = (CGRect){frame.origin.x,frame.origin.y,frame.size.width,frame.size.height};
            self.alpha = 1;
        }];
    }
    return self;
}

+(instancetype)showWithMessege:(NSString *)msg duration:(NSTimeInterval)duration{
    return [self showWithMessege:msg distanceToBotton:defaultDistanceToBotton duration:duration hiddenComplete:nil];
}

+(instancetype)showWithMessege:(NSString*)msg duration:(NSTimeInterval)duration hiddenComplete:(void(^)())complete{
    return [self showWithMessege:msg distanceToBotton:defaultDistanceToBotton duration:2 hiddenComplete:complete];
}

+(instancetype)showWithMessege:(NSString*)msg distanceToBotton:(CGFloat)distance duration:(NSTimeInterval)duration hiddenComplete:(void(^)())complete{
    __block Toast * t = [self Toat:msg duration:duration];
    t.frame =  CGRectMake(20, [UIScreen mainScreen].bounds.size.height - distance, [UIScreen mainScreen].bounds.size.width - 40, 30);
    t.hiddenComplete = complete;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [UIView animateWithDuration:0.2 animations:^{
            t.frame = (CGRect){t.frame.origin.x,t.frame.origin.y+distance,t.frame.size.width,t.frame.size.height};
            t.alpha = 0;
        }completion:^(BOOL finished) {
            [t removeFromSuperview];
            if(t.hiddenComplete)t.hiddenComplete();
        }];
    });
    return t;
}
@end

CGFloat const defaultDistanceToBotton = 100;
CGFloat const defaultDistanceToTop = 40;
